﻿using System.Data;
using System.Net;
using System.Web.Services.Protocols;
using System.Xml;

namespace Citi.Helpers
{
    public class SharePointHelper
    {
        private static SoapHttpClientProtocol SharepointService { get; set; }

        public static DataTable GetLists(SoapHttpClientProtocol sharepointService, string url, string listName)
        {
            SharepointService = sharepointService;
            SharepointService.PreAuthenticate = true;
            SharepointService.UseDefaultCredentials = true;
            SharepointService.Url = url + @"/_vti_bin/lists.asmx";

            foreach (XmlNode list in ((XmlNode)SharepointService.GetType().GetMethod("GetListCollection").Invoke(SharepointService, null)).ChildNodes)
            {
                string title = list.Attributes["Title"].Value;

                if (title != listName) continue;

                return GetListItems(SharepointService,SharepointService.Url , title, null);
            }
            
            return null;
        }

        public static DataTable GetListItems(SoapHttpClientProtocol sharepointService,string url,  string listName, string viewName = null)
        {
            XmlTextReader reader = null;
            DataSet dataSet = null;

            if (SharepointService == null)
            {
                SharepointService = sharepointService;
                SharepointService.PreAuthenticate = true;
                SharepointService.UseDefaultCredentials = true;
                SharepointService.Url = url + @"/_vti_bin/lists.asmx";
            }

            try
            {
                XmlNode rez = (XmlNode)SharepointService.GetType().GetMethod("GetListItems").Invoke(SharepointService, new[] { listName, viewName, null, null, null, null, string.Empty });
                reader = new XmlTextReader(rez.OuterXml, XmlNodeType.Element, null);
            }
            catch
            {

            }

            dataSet = new DataSet();
            dataSet.ReadXml(reader);
            if (dataSet.Tables["row"] != null)
                return dataSet.Tables["row"];
        
            return null;
        }
    }
}
